import React, { useState, useEffect } from 'react';
import styles from '../css/scenicdetails.module.css';
import { Switch } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import right from '../assets/right.png';
import start from '../assets/graystar.png';
import starts from '../assets/starts.png';
import love2 from '../assets/love2.png';
import lovered from '../assets/love-red.png';
import dian from '../assets/point.png';
import left from '../assets/left.png';
import have from '../assets/vioce.png';
import grayright from '../assets/garyright.png';
import { imgUrl } from '../config'; // 导入imgUrl
import {
    fetchCollectList,
    toggleCollection,
    toggleLike
} from '../api/ticketApi';
import {
    getScenicTickets
} from '../api/scenicData';
const Tickets = () => {
    // 状态管理
    const [data, setData] = useState(null);
    const [videoMusic, setVideoMusic] = useState(false);
    const [showAlert, setShowAlert] = useState(false);
    const [alertContent, setAlertContent] = useState('');
    const [isCollect, setIsCollect] = useState(false);
    const [isLike, setIsLike] = useState(false);
    const [activeTab, setActiveTab] = useState(null);
    const [showMedia, setShowMedia] = useState('video');
    const navigate = useNavigate();
    
    // 从 sessionStorage 获取数据
    const scenic_id = sessionStorage.getItem("jingid");
    const userid = sessionStorage.getItem("userid");
    const img = sessionStorage.getItem("img");
    const videos = sessionStorage.getItem("video");

    // 初始化数据
    useEffect(() => {
        // 设置媒体资源
        const videoElement = document.querySelector('video');
        const imgElement = document.querySelector('img');
        if (videoElement) videoElement.src = videos;
        if (imgElement) imgElement.src = img;

        // 获取数据
        const fetchData = async () => {
            try {
                const [ticketRes, collectRes] = await Promise.all([
                    getScenicTickets(scenic_id),
                    fetchCollectList(userid)
                ]);
                
                console.log('门票数据:', ticketRes);
                sessionStorage.setItem("alertdata", JSON.stringify(ticketRes.data));
                setData(ticketRes.data);
                
                console.log('收藏列表:', collectRes);
                
                // 检查收藏和点赞状态
                const collectStatus = sessionStorage.getItem("collectStatus");
                const loveStatus = sessionStorage.getItem("love");
                setIsCollect(collectStatus === "1");
                setIsLike(loveStatus === "1");
            } catch (error) {
                console.error('获取数据时出错:', error);
            }
        };

        fetchData();
    }, []);

    // 渲染门票
    const renderTickets = () => {
        if (!data) return null;
       
        let ticketsToRender = [];
        if (activeTab === null) {
            data.forEach(item => {
                if (item.children) {
                    ticketsToRender = ticketsToRender.concat(item.children);
                }
            });
        } else {
            ticketsToRender = data[activeTab].children || [];
        }

        return ticketsToRender.map((item, i) => (
            <div key={i} style={{ marginTop: '5px' }}>
                <div className={styles.adult}>
                    <div>
                        <b>{item.name}</b>
                        <del>￥{item.original_price || '无定价'}</del>
                    </div>
                </div>
                <div className={styles.day}>
                    <div>
                        <span style={{ marginLeft: '10px', color: '#0aa1f9' }}>可订明日</span>
                        <p style={{ fontSize: '13px', color: 'red' }}>
                            ￥<span style={{ fontSize: '16px' }}>{item.current_price || '无定价'}</span>
                            <span style={{ fontSize: '15px', color: '#535453' }}>起</span>
                        </p>
                    </div>
                </div>
                <div className={styles.retreat}>
                    <div>
                        <span style={{ marginLeft: '10px', color: '#0aa1f9' }}>随时退，无需退票</span>
                        <p>优惠￥10</p>
                    </div>
                </div>
                <div className={styles.reserve}>
                    <div>
                        <span
                            style={{ marginLeft: '10px', color: '#535453' }}
                            onClick={() => handleGobuy(i)}
                        >
                            购买须知<img style={{ marginTop: '5px' }} src={grayright} alt="" />
                        </span>
                        <p onClick={() => handleReserve(i)}>预定</p>
                    </div>
                </div>
                {i < ticketsToRender.length - 1 && (
                    <div style={{ borderBottom: '1px solid #e0e0e0', margin: '10px 0' }}></div>
                )}
            </div>
        ));
    };

    // 处理预定
    const handleReserve = (i) => {
        if (!data) return;
        let ticketsToReserve = [];
        if (activeTab === null) {
            data.forEach(item => {
                if (item.children) {
                    ticketsToReserve = ticketsToReserve.concat(item.children);
                }
            });
        } else {
            ticketsToReserve = data[activeTab].children || [];
        }
        
        const reservedTicket = ticketsToReserve[i];
        if (!reservedTicket) {
            console.error('Invalid ticket data at index:', i);
            return;
        }

        sessionStorage.setItem('reservedTicket', JSON.stringify(reservedTicket));
        navigate('/suborder');
    };

    // 处理购买须知
    const handleGobuy = (i) => {
        if (!data) return;
        let ticketsToBuy = [];
        if (activeTab === null) {
            data.forEach(item => {
                if (item.children) {
                    ticketsToBuy = ticketsToBuy.concat(item.children);
                }
            });
        } else {
            ticketsToBuy = data[activeTab].children || [];
        }
        
        const ticket = ticketsToBuy[i];
        if (!ticket) {
            console.error('Invalid ticket data at index:', i);
            return;
        }
        
        setAlertContent(ticket.deatils || '暂无购买须知');
        setShowAlert(true);
    };

    // 关闭弹窗
    const handleShut = () => {
        setShowAlert(false);
    };

    // 切换媒体显示
    const handleImgBtns = () => {
        setShowMedia('image');
    };

    const handleVideoBtns = () => {
        setShowMedia('video');
    };

    // 静音控制
    const handleMusic = () => {
        setVideoMusic(!videoMusic);
        const video = document.getElementById('videos');
        if (video) {
            video.muted = !videoMusic;
        }
    };

    // 返回上一页
    const handleLeft = () => {
        window.history.back();
    };

    // 收藏功能
    const handleStart = async () => {
        try {
            const res = await toggleCollection(userid, 1);
            if (res.data === 1) {
                setIsCollect(true);
                sessionStorage.setItem("collectStatus", "1");
            } else if (res.data === 2) {
                setIsCollect(false);
                sessionStorage.setItem("collectStatus", "0");
            }
        } catch (error) {
            console.error('收藏操作时出错:', error);
        }
    };

    // 点赞功能
    const handleLove = async () => {
        try {
            const res = await toggleLike(userid, 3);
            if (res.data === 1) {
                sessionStorage.setItem("love", "1");
                setIsLike(true);
            } else if (res.data === 2) {
                sessionStorage.setItem("love", "0");
                setIsLike(false);
            }
        } catch (error) {
            console.error('点赞操作时出错:', error);
        }
    };

    // 门票选项卡
    const renderTabs = () => {
        if (!data) return null;

        return data.map((item, i) => (
            <div
                key={i}
                onClick={() => setActiveTab(i)}
                className={activeTab === i ? styles.activeTab : ''}
            >
                {item.name}
            </div>
        ));
    };

    // 相册跳转
    const handlePhotoAlbum = () => {
        navigate("/photoAlbum");
    };

    // 渲染收藏图标
    const renderCollectIcon = () => {
        return (
            <div className={styles.rights} onClick={handleStart}>
                <img
                    id="startImg"
                    src={isCollect ? start : starts}
                    alt="收藏图标"
                />
            </div>
        );
    };

    return (
        <div style={{ backgroundColor: '#f4f4f4', height: '100vh' }}>
            {/* 提示消息组件 */}
            <div className={`${styles.revamp} ${isCollect ? styles.show : ''}`}>
                <div className={styles.revamps}>
                    <div className={styles.revampone}>收藏成功！</div>
                </div>
            </div>

            <div className={`${styles.collect} ${!isCollect ? styles.show : ''}`}>
                <div className={styles.collects}>
                    <div className={styles.collectone}>已取消收藏！</div>
                </div>
            </div>

            <div className={`${styles.likesuccess} ${isLike ? styles.show : ''}`}>
                <div className={styles.like}>
                    <div className={styles.likeone}>已点赞！</div>
                </div>
            </div>

            <div className={`${styles.likeno} ${!isLike ? styles.show : ''}`}>
                <div className={styles.nolike}>
                    <div className={styles.nolikeone}>已取消！</div>
                </div>
            </div>

            {/* 购买须知弹窗 */}
            {showAlert && (
                <div className={styles.alertOverlay}>
                    <div className={styles.alertContent}>
                        <div className={styles.alertone}>
                            <p>购买须知</p>
                            <div dangerouslySetInnerHTML={{ __html: alertContent }} />
                            <div className={styles.close} onClick={handleShut}>关闭</div>
                        </div>
                    </div>
                </div>
            )}

            {/* 主内容 */}
            <div className={styles.big}>
                <div className={styles.image}>
                    <div className={styles.images}>
                        <img
                            src={`${imgUrl}${img}`}
                            alt="景区图片"
                            style={{ display: showMedia === 'image' ? 'block' : 'none' }}
                        />
                        <video
                            id="videos"
                            src={`${imgUrl}${videos}`}
                            controls
                            autoPlay
                            loop
                            playsInline
                            style={{ display: showMedia === 'video' ? 'block' : 'none' }}
                        ></video>
                    </div>

                    {/* 顶部导航 */}
                    <div className={styles.tops}>
                        <div className={styles.lefts} onClick={handleLeft}>
                            <img src={left} alt="返回" />
                        </div>
                        <div className={styles.threes}>
                            {renderCollectIcon()}
                            <div className={styles.rights} onClick={handleLove}>
                                <img
                                    id="lover"
                                    src={isLike ? lovered : love2}
                                    alt="点赞"
                                />
                            </div>
                            <div className={styles.rights}>
                                <img src={dian} alt="更多" />
                            </div>
                        </div>
                    </div>

                    {/* 底部控制栏 */}
                    <div className={styles.bottoms}>
                        <div className={styles.bottom}>
                            <div className={styles.vAndi}>
                                <Switch
                                    checked={showMedia === 'video'}
                                    onChange={(checked) => {
                                        checked ? handleVideoBtns() : handleImgBtns();
                                    }}
                                    checkedText="视频"
                                    uncheckedText="图片"
                                    activeColor="#FFFFFF"
                                    inactiveColor="#5F5B50"
                                />
                            </div>
                            <div className={styles.photo} onClick={handlePhotoAlbum}>
                                <span>相册</span>
                                <img src={right} alt="相册" />
                            </div>
                            <div className={styles.music} onClick={handleMusic}>
                                <img
                                    id="musics"
                                    src={have}
                                    alt="静音控制"
                                />
                            </div>
                        </div>
                    </div>
                </div>

                {/* 门票区域 */}
                <div className={styles.ticket}>
                    <b>门票</b>
                    <div className={styles.small}>
                        {renderTabs()}
                    </div>
                </div>

                <div className={styles.ticketTwo}>
                    <b>门票</b>
                    <div className={styles.two_block}>
                        {renderTickets()}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Tickets;